import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import { useState,useEffect,useRef } from 'react'
import styles from './index.module.scss'
import { Toast } from 'antd-mobile'
import { io } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { getTokenInfo } from '@/utils/storage'

type Message = {
  // 用于区别消息类型的 type
  type?: 'robot' | 'user'
  msg: string
  timestamp: number
}
export default function ProfileChat() {
  const [msg, setMsg] = useState('')
   // 聊天列表
  //  const [list, setList] = useState<Message[]>([
  //   { type: 'robot', msg: '亲爱的用户您好，小智同学为您服务。', timestamp: Date.now() },
  //   { type: 'user', msg: '你好啊。', timestamp: Date.now()+1},
  // ])
  const [list, setList] = useState<Message[]>([])
 const handleSend=()=>{
   // 空提示
   if (!msg) return Toast.show({ content: '请输入内容！' })
  const userMsg: Message = {
         type: 'user',
         msg: msg,
         timestamp: Date.now(),
       }
       clientRef.current.emit('message', userMsg)
        // 后追加用户消息
        setList([...list, userMsg])
        setMsg('')
 }
 const clientRef = useRef<any>(null)
 useEffect(() => {
  // 创建 socket.io 客户端实例
  const client = io(baseURL, {
    query: {
      token: getTokenInfo().token,
    },
    transports: ['websocket'],
  })

  // 连接
  clientRef.current = client
  client.on('connect', () => {
    // console.log('websocket连接成功+++')
    setList([
      { type: 'robot', msg: '亲爱的用户您好，小智同学为您服务。', timestamp: Date.now() },
      { type: 'user', msg: '你好啊。', timestamp: Date.now() + 1 },
    ])
  })
  client.on('message', (data) => {
    setList((oldList) => {
      return [...oldList, { type: 'robot', ...data }]
    })
  })

  // 清理函数
  return () => {
    // 需要主动关闭连接
    client.close()
  }
}, [])

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      {/* <NavBar>小智同学</NavBar> */}
      <NavBar fixed>小智同学</NavBar>
      {/* 聊天记录列表 - 开始 */}
      <div className='chat-list'>
      {list.map((item) => {
          // 通过 type 区分消息类型
          if (item.type === 'robot') {
            return (
              <div key={item.timestamp} className='chat-item robot'>
                <Icon type='iconbtn_xiaozhitongxue' />
                <div className='message'>{item.msg}</div>
              </div>
            )
          } else {
            return (
              <div key={item.timestamp} className='chat-item user'>
                <img src={'http://toutiao.itheima.net/images/user_head.jpg'} alt='' />
                <div className='message'>{item.msg}</div>
              </div>
            )
          }
        })}
      </div>
      {/* 聊天记录列表 - 结束 */}

      {/* 底部消息输入框 */}
      <div className='footer'>
        <div className='input-footer'>
          <Icon type='iconbianji' />
          <Input autoFocus className='no-border' placeholder='请描述您的问题'  value={msg} onChange={(e) => setMsg(e.target.value)}/>
          <span className='send' onClick={handleSend}>发送</span>
        </div>
      </div>
    </div>
  )
}